package com.ruoyi.common.core.delay;

import lombok.Data;
import org.springframework.data.redis.core.TimeoutUtils;

import java.util.Date;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 延时任务
 * @Author: wyx
 * @Date: 2023/5/29 20:45
 */
@Data
public class ItemDelayed<T> implements Delayed {
    /**默认延迟60秒*/
    private long timeout ;
    /**数据id*/
    private Long dataId;
    /**开始时间*/
    private long startTime;
    /**到期时间*/
    private long expire;
    /**创建时间*/
    private Date now;
    /**泛型data*/
    private T data;

    public ItemDelayed(Long dataId, long startTime, T data, Long timeout, TimeUnit timeUnit) {
        super();
        this.timeout = TimeoutUtils.toMillis(timeout, timeUnit);
        this.dataId = dataId;
        this.startTime = startTime;
        this.expire = startTime + this.timeout;
        this.now = new Date();
        this.data = data;

    }

    @Override
    public int compareTo(Delayed o) {
        return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.expire - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }
}
